package com.jastar.android.test.demo;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import com.jastar.android.test.R;
import com.jastar.android.test.abstracts.AbstractExamActivity;
import com.jastar.android.util.AudioPlayer;
import com.jastar.android.util.FileUtil;
import com.jastar.android.util.RandomUtil;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class WordsActivity extends AbstractExamActivity {
    private List<String> words;

    @Override
    protected void beforeRender() {
        super.beforeRender();
        List<String> lines = FileUtil.readRawLines(getResources(), R.raw.words);
        words = lines.parallelStream().map(line -> line.split("\\|")[0]).collect(Collectors.toList());
        button_answers.forEach(b -> b.post(() -> {
            // 在视图完成布局后获取实际宽度
            ViewGroup.LayoutParams params = b.getLayoutParams();
            params.height = b.getWidth();
            b.setLayoutParams(params);
        }));
    }

    @Override
    protected int getActivityId() {
        return R.layout.activity_words;
    }

    @Override
    protected QuestionItem getNextQuestionItem(int answerCount) {
        QuestionItem item = new QuestionItem();

        //先从所有words随机取四个，做为答案列表
        int[] words_index_ary = RandomUtil.randomNumber(0, words.size() - 1, 4);
        Arrays.stream(words_index_ary).forEach(i -> {
            int id = getDrawableByWord(words.get(i));
            item.answers.add(id);
        });

        //再从答案中随机取一个，做为问题和正确答案
        int index_index = random.nextInt(words_index_ary.length);
        String word = words.get(words_index_ary[index_index]);
        item.rightAnswer = item.answers.get(index_index);
        item.question = word;

        int id = getResources().getIdentifier(getNameByWord(word), "raw", getPackageName());
        AudioPlayer.getPlayer().play(this, id);

        return item;
    }

    @Override
    protected void setButtonByAnswer(View v, Object answer) {
        ImageButton button = (ImageButton) v;
        button.setImageResource((int) answer);
        button.setTag(answer);
    }

    @Override
    protected boolean isRightAnswer(View v, Object answer) {
        ImageButton button = (ImageButton) v;
        return button.getTag().equals(answer);
    }

    private int getDrawableByWord(String word) {
        return getResources().getIdentifier(getNameByWord(word), "drawable", getPackageName());
    }

    public static String getNameByWord(String word) {
        String name = word;
        if (name.contains(" ")) name = name.replace(" ", "_");//词组空格替换为下划线
        if (name.equals("short")) name = "short_";//兼容系统关键字
        return name;
    }

    @Override
    protected void onPause() {
        super.onPause();
        AudioPlayer.getPlayer().stop();
    }

}